package System.machine;

import patterns.Status.MachineStatus;

abstract class BaseFarmMachine implements FarmMachine {
    protected String machineId;
    protected MachineStatus currentStatus;
    protected double fuelLevel;
    protected String location;
    protected String currentTask;

    public BaseFarmMachine(String machineId) {
        this.machineId = machineId;
        this.currentStatus = MachineStatus.IDLE;
        this.fuelLevel = 100.0; // 初始油量100%
        this.location = "仓库";
        this.currentTask = "无";
    }

    @Override
    public String getMachineId() {
        return machineId;
    }

    @Override
    public void updateStatus(MachineStatus status) {
        this.currentStatus = status;
        System.out.printf("农机 %s 状态更新为: %s (%s)%n",
                machineId, status.getDescription(), status.getActionHint());

        // 低油量自动检测
        if (fuelLevel < 15.0 && status != MachineStatus.LOW_FUEL) {
            this.currentStatus = MachineStatus.LOW_FUEL;
            System.out.printf("警告: 农机 %s 油量过低 (%.1f%%)%n", machineId, fuelLevel);
        }
    }

    @Override
    public MachineStatus getCurrentStatus() {
        return currentStatus;
    }

    @Override
    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public String getLocation() {
        return location;
    }

    @Override
    public void setFuelLevel(double level) {
        this.fuelLevel = Math.max(0, Math.min(100, level));
        System.out.printf("农机 %s 油量更新为: %.1f%%%n", machineId, fuelLevel);

        // 油量变化可能影响状态
        if (fuelLevel < 15.0) {
            updateStatus(MachineStatus.LOW_FUEL);
        } else if (currentStatus == MachineStatus.LOW_FUEL && fuelLevel >= 15.0) {
            updateStatus(MachineStatus.IDLE);
        }
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public String getCurrentTask() {
        return currentTask;
    }

    @Override
    public void assignTask(String task) {
        if (!currentStatus.isAvailable()) {
            System.out.printf("无法分配任务: 农机 %s 当前状态为 %s%n",
                    machineId, currentStatus.getDescription());
            return;
        }

        this.currentTask = task;
        updateStatus(MachineStatus.WORKING);
        System.out.printf("农机 %s 已分配任务: %s%n", machineId, task);
    }

    @Override
    public void displayStatus() {
        System.out.println("=== 农机状态详情 ===");
        System.out.println("农机ID: " + machineId);
        System.out.println("类型: " + getMachineType());
        System.out.println("状态: " + currentStatus.getDescription());
        System.out.println("状态提示: " + currentStatus.getActionHint());
        System.out.printf("油量: %.1f%%%n", fuelLevel);
        System.out.println("位置: " + location);
        System.out.println("当前任务: " + currentTask);
        System.out.println("=================");
    }
}